package com.bdqn.mzc.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bdqn.mzc.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器验证是否已登录
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("******************拦截器已执行******************");
        //获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            //验证令牌
            DecodedJWT jwt = JWTUtils.verify(token);
        }catch (SignatureVerificationException e){
            throw new TokenExpiredException("无效签名");
        }catch (TokenExpiredException e){
            throw new TokenExpiredException("token过期");
        }catch (AlgorithmMismatchException e){
            throw new TokenExpiredException("token算法不一致");
        }catch (Exception e){
            throw new TokenExpiredException("token无效");
        }
        return true;//放行请求
    }
}
